package com.example.demo.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.example.demo.VO.PermissionsVO;
import com.example.demo.dao.PermissionsMapper;
import com.example.demo.entity.Permissions;
import com.example.demo.service.IPermissionsService;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hanfei
 * @since 2020-04-08
 */
@Service
public class PermissionsServiceImpl extends ServiceImpl<PermissionsMapper, Permissions> implements IPermissionsService {
        @Resource
        public PermissionsMapper mapper;

        public PermissionsMapper getMapper() {
        return mapper;
        }

        public void setMapper(PermissionsMapper mapper) {
        this.mapper = mapper;
        }

        public Page<Permissions> findByKey(Page<Permissions> var1, @Param("key") String key){
        var1.setRecords(mapper.findByKey(var1,key));
        return var1;
        }
        public Page<Permissions> findByKeyAndAll(Page<Permissions> var1, @Param("key") String key, Permissions entity){
        var1.setRecords(mapper.findByKeyAndAll(var1,key,entity));
        return var1;
        }

        public  List<PermissionsVO> getChild(String id, List<PermissionsVO> rootMenu){
                List<PermissionsVO> childList = new ArrayList<>();
                for (PermissionsVO menu : rootMenu) {
                        // 遍历所有节点，将父菜单id与传过来的id比较
                        if (StringUtils.isNotBlank(menu.getPid())) {
                                if (menu.getPid().equals(id)) {
                                        childList.add(menu);
                                }
                        }
                }
                // 把子菜单的子菜单再循环一遍
                for (PermissionsVO menu : childList) {// 当子菜单的id作为其他菜单的pid的时候，具备子菜单，需要实现递归查询
                        for (PermissionsVO menu1 : rootMenu) {
                                if (StringUtils.isNotBlank(menu1.getPid())) {
                                        if (menu1.getPid().equals(menu.getId())) {
                                                // 递归
                                                menu.setChildTDPermissions(getChild(menu.getId(), rootMenu));
                                        }
                                }
                        }
                } // 递归退出条件
                if (childList.size() == 0) {
                        return null;
                }
                return childList;

        }
        public List<PermissionsVO> findall(){
                return mapper.findall();
        }
        }
